package com.interest.controller;

import com.interest.controller.builder.ErrorModelAndViewBuilder;
import com.interest.modules.account.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/reg")
public class RegController {

    @Autowired
    private AccountService accountService;

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView reg(@RequestParam(value = "username") String username,
                            @RequestParam(value = "password") String password,
                            @RequestParam(value = "rpassword") String rpassword, HttpSession httpSession) {
        if (username == null || "".equals(username)) {
            return new ErrorModelAndViewBuilder("用户名不能为空").build();
        } else if (password == null || password.length() < 6) {
            return new ErrorModelAndViewBuilder("密码格式不对").build();
        } else if (!password.equals(rpassword)) {
            return new ErrorModelAndViewBuilder("两次输入的密码不相同").build();
        } else {
            int ret = accountService.regAccount(username, password);
            if (ret == 0) {
                httpSession.setAttribute("account", username);
                return new ModelAndView("redirect:/github/trending/list");
            } else {
                return new ErrorModelAndViewBuilder("该账号已经被注册").build();
            }
        }

    }
}
